package com.opdar.athena.client.agent.controllers;

import com.opdar.athena.base.RedisSessionManager;
import com.opdar.athena.client.agent.annotations.Commond;
import com.opdar.athena.client.agent.annotations.MessageType;
import com.opdar.athena.client.agent.base.Configuration;
import com.opdar.athena.client.agent.base.TcpSessionManager;
import com.opdar.athena.client.agent.server.IoSession;
import com.opdar.athena.entities.MessageEntity;
import com.opdar.athena.entities.ProjectEntity;
import com.opdar.athena.entities.UserEntity;
import com.opdar.athena.mapper.MessageMapper;
import com.opdar.athena.mapper.ProjectMapper;
import com.opdar.athena.messages.UserMessage;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by shiju on 2017/6/29.
 */
@MessageType(value = UserMessage.class, type = com.opdar.athena.base.MessageType.USER)
public class UserController {

    @Autowired
    private TcpSessionManager tcpSessionManager;

    @Autowired
    private RedisSessionManager redisSessionManager;
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    MessageMapper messageMapper;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * bind on client
     */
    @Commond("BindWithToken")
    public Object bindWithToken(IoSession session, UserMessage message) {
        logger.info("正在绑定Token[{}]",message.getToken());
        session.setToken(message.getToken());
        tcpSessionManager.set(message.getToken(),session, Configuration.getConfiguration().getHeartbeatTime());

        UserEntity user = redisSessionManager.get(message.getToken());
        ProjectEntity project = new ProjectEntity();
        project.setAppId(user.getAppId());
        project = projectMapper.selectOne(project);
        if(project.getAcceptOfflineMessage() !=null && project.getAcceptOfflineMessage() == 0){
            //该项目接受离线消息
            MessageEntity _message = new MessageEntity();
            _message.setReciver(user.getId());
            _message.setStat(1);
            List<MessageEntity> list = messageMapper.selectList(_message);
            //已发送
            final List<String> where = new LinkedList<String>();
            for(MessageEntity messageEntity:list){
                where.add(messageEntity.getId());
            }
            if(list.size() > 0){
                session.write(com.opdar.athena.base.MessageType.MESSAGE,list,project.getDomain()).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        if(channelFuture.isSuccess()){
                            MessageEntity update = new MessageEntity();
                            update.setStat(2);
                            messageMapper.batchUpdateById(update,where);
                        }
                    }
                });
            }
        }
        return null;
    }

    @Commond("BindWithMigrate")
    public Object bindWithMigrate(IoSession session, UserMessage message) {
        logger.info("BindWithMigrate Token[{}]",message.getToken());
        redisSessionManager.useMigrate(message.getMigrateId(),message.getToken());
        return bindWithToken(session,message);
    }

    @Commond("Count")
    public Object count(IoSession session, UserMessage message) {
        return tcpSessionManager.size();
    }

    /**
     * message agent registry
     */
    @Commond("MessageAgentRegist")
    public Object messageAgentRegist(IoSession session, UserMessage message) {
        session.setAgent(true,message.getToken());
        tcpSessionManager.set(message.getToken(),session, Configuration.getConfiguration().getHeartbeatTime());
        return null;
    }

}
